<?php
if(!defined('IN_DISCUZ') || !defined('IN_ADMINCP')) {
	exit('Access Denied');
}

global $_G;

$plang = lang('plugin/unifiedpay');

require_once DISCUZ_ROOT . 'source/plugin/unifiedpay/function/function_base.php';

if(submitcheck('querysubmit')) {
	$order_id = intval($_GET['order_id']);
	$referer = $_GET['referer'];
	if(!$referer) $referer = 'action=plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders';
	$result = unifiedpay_query_order($order_id);
	if($result['code'] == 200) {
		cpmsg('payment_succeed', $referer, 'succeed');
	} else {
		cpmsg($result['message'], '', 'error');
	}
} elseif(submitcheck('refundsubmit')) {
	$order_id = intval($_GET['order_id']);
	$refund_amount = $_GET['refund_amount'];
	$refund_desc = $_GET['refund_desc'];
	$referer = $_GET['referer'];
	if(!$referer) $referer = 'action=plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders';
	if(!is_numeric($refund_amount) || !preg_match('/^[0-9.]+$/', $refund_amount) || $refund_amount == 0) {
		cpmsg($plang['refund_amount_error'], '', 'error');
	}
	$order = C::t('common_payment_order')->fetch($order_id);
	$result = unifiedpay_refund($order['out_biz_no'], $order_id, strval($refund_amount*100), $refund_desc);
	if($result['code'] == 200) {
		cpmsg(sprintf($plang['refund_succeed'], $refund_amount), $referer, 'succeed');
	} else {
		cpmsg($result['message'], '', 'error');
	}
} elseif($_GET['op'] == 'retry') {
	$order_id = intval($_GET['order_id']);
	$order = C::t('common_payment_order')->fetch($order_id);
	$result = payment::retry_callback_order($order);
	if($result['code'] == 200) {
		cpmsg('payment_succeed', $_G['siteurl'] . ADMINSCRIPT . '?action=plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders', 'succeed');
	} else {
		cpmsg($result['message'], $_G['siteurl'] . ADMINSCRIPT . '?action=plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders', 'error');
	}
} elseif($_GET['op'] == 'query') {
	$order_id = intval($_GET['order_id']);
	$order = C::t('common_payment_order')->fetch($order_id);

	$channels = payment::channels();

	if($order['uid']>0){
		$user = getuserbyuid($order['uid']);
		$username = $user['username'];
	}else{
		$username = '游客';
	}

	if(!$order['status'] && $order['expire_time'] < time()) {
		$order['status'] = 2;
	}

	$amountstr = number_format($order['amount'] / 100, 2, '.', ',');
	if($order['status'] == 3) {
		$refund_list = C::t('common_payment_refund')->sum_by_orders(array($order_id));
		$order['refund_amount'] = $refund_list[$order_id]['amount'];
		$amountstr .= '<br/>' . $lang['ec_paymentorders_refund_amount'] . ':' . number_format($order['refund_amount'] / 100, 2, '.', ',');
	}

	echo '<style type="text/css">span.order-status-0 { color: #555; } span.order-status-1 { color: green; } span.order-status-2 { color: #ccc; } span.order-status-3 { color: #fe6666; }</style>';
	showtableheader('ec_paymentorders_detail');
	
	showsetting('ec_paymentorders_no', '', '', $order['out_biz_no']);
	if($order['status'] > 0 && $order['status'] != 2){
		showsetting($plang['ec_paymentorders_api_no'], '', '', $order['trade_no']);
	}
	showsetting('ec_paymentorders_type', '', '', $order['type_name']);
	showsetting('ec_paymentorders_desc', '', '', $order['subject'] . ($order['description'] ? '<br/>' . $order['description'] : ''));
	$payer = '';
	if($order['payer']) {
		$payer = '<br/>' . $plang['payment_payer_'.$order['payer']] . $order['payer'];
	}
	showsetting('ec_paymentorders_user', '', '', $username . ' (' . $order['uid'] . ')' . '<br/>' . $order['clientip'] . ':' . $order['remoteport'] . $payer);
	showsetting('ec_paymentorders_amount', '', '', $amountstr);
	showsetting('ec_paymentorders_channel', '', '', $channels[$order['channel']]['title']);
	if($order['plugin']){
		showsetting($plang['ec_paymentorders_plugin'], '', '', $plang['payment_plugin_'.$order['plugin']]);
	}
	showsetting('ec_orders_submitdate', '', '', date('Y-m-d H:i:s', $order['dateline']));
	if($order['status'] > 0 && $order['status'] != 2){
		showsetting('ec_orders_confirmdate', '', '', date('Y-m-d H:i:s', $order['payment_time']));
	}
	showsetting('ec_paymentorders_status', '', '', '<span class="order-status-'.$order['status'].'">'.$lang['ec_paymentorders_status_' . $order['status']].'<span>');

	if($order['status'] == 0 || $order['status'] == 2){
		showformheader('plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders');
		showhiddenfields(array('order_id' => $order['id'], 'referer' => $_SERVER['HTTP_REFERER']));
		showsubmit('querysubmit', $plang['ec_query_order_submit'], '', $lang['ec_paymentorders_query_submit_tips']);
		showformfooter();
	}
	if($order['status'] == 1){
		showtablefooter();
		showtableheader($plang['ec_paymentorders_refund']);
		showformheader('plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders', 'onsubmit="return confirm(\''.$plang['ec_refund_confirm'].'\')"');
		showhiddenfields(array('order_id' => $order['id'], 'referer' => $_SERVER['HTTP_REFERER']));
		showsetting($plang['ec_refund_amount'], 'refund_amount', sprintf('%.2f', $order['amount'] / 100), 'text', '', 0, $plang['ec_refund_amount_comment']);
		showsetting($plang['ec_refund_desc'], 'refund_desc', '', 'text');
		showsubmit('refundsubmit', $plang['ec_refund_order_submit']);
		showformfooter();
	}
	
	showtablefooter();
	
} else {
	$start_limit = ($page - 1) * $_G['tpp'];

	echo '<style type="text/css">.order-status-0 td { color: #555; } .order-status-1 td { color: green; } .order-status-2 td, .order-status-2 td a { color: #ccc; } .order-status-3 td { color: #fe6666; } a.order-retry{ color: #fe6666; }</style>';
	echo '<script src="static/js/calendar.js" type="text/javascript"></script>';
	$queryparams = array(
		'out_biz_no' => daddslashes($_GET['out_biz_no']),
		'user' => daddslashes($_GET['user']),
		'type' => daddslashes($_GET['type']),
		'channel' => daddslashes($_GET['channel']),
		'status' => daddslashes($_GET['status']),
		'starttime' => daddslashes($_GET['starttime']),
		'endtime' => daddslashes($_GET['endtime']),
	);

	$types = C::t('common_payment_order')->fetch_type_all();
	$typeoptions = array();
	$typeoptions[] = '<option value="">' . $lang['all'] . '</option>';
	foreach($types as $k => $v) {
		$typeoptions[] = "<option value=\"{$k}\"" . ($k == $queryparams['type'] ? ' selected' : '') . ">{$v}</option>";
	}
	showformheader('plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders');
	showtableheader('ec_paymentorders_search');
	showtablerow('', array(
		'style="width:100px"', 'style="width:200px"',
		'style="width:100px"', 'style="width:200px"',
		'style="width:100px"', ''
	),
		array(
			lang('admincp', 'ec_orders_search_id'), '<input type="text" class="txt" name="out_biz_no" value="' . $queryparams['out_biz_no'] . '" />',
			lang('admincp', 'ec_paymentorders_user'), '<input type="text" class="txt" name="user" value="' . $queryparams['user'] . '" />',
			lang('admincp', 'ec_paymentorders_type'), '<select name="type">' . implode('', $typeoptions) . '</select>',
		)
	);

	$channels = payment::channels();
	$channeloptions = array();
	$channeloptions[] = '<option value="">' . $lang['all'] . '</option>';
	foreach($channels as $channel) {
		$channeloptions[] = '<option value="' . $channel['id'] . '"' . ($queryparams['channel'] == $channel['id'] ? ' selected' : '') . '>' . $channel['title'] . '</option>';
	}
	$statusoptions = array();
	$statusoptions[] = '<option value="">' . $lang['all'] . '</option>';
	$statusoptions[] = '<option value="0"' . ($queryparams['status'] === '0' ? ' selected' : '') . '>' . $lang['ec_paymentorders_status_0'] . '</option>';
	$statusoptions[] = '<option value="1"' . ($queryparams['status'] === '1' ? ' selected' : '') . '>' . $lang['ec_paymentorders_status_1'] . '</option>';
	$statusoptions[] = '<option value="2"' . ($queryparams['status'] === '2' ? ' selected' : '') . '>' . $lang['ec_paymentorders_status_2'] . '</option>';
	showtablerow('', array(),
		array(
			lang('admincp', 'ec_paymentorders_channel'), '<select name="channel">' . implode('', $channeloptions) . '</select>',
			lang('admincp', 'ec_paymentorders_status'), '<select name="status">' . implode('', $statusoptions) . '</select>',
			lang('admincp', 'ec_paymentorders_date'), '<input type="text" class="txt" name="starttime" value="' . $queryparams['starttime'] . '" style="width: 108px;" onclick="showcalendar(event, this)"> - <input type="text" class="txt" name="endtime" value="' . $queryparams['endtime'] . '" style="width: 108px;" onclick="showcalendar(event, this)"><input class="btn" type="submit" value="'.$lang['search'].'" />',
		)
	);

	showtablefooter();
	if($queryparams['user']) {
		if(preg_match('/^\d+$/', $queryparams['user'])) {
			$queryparams['uid'] = $queryparams['user'];
		} else {
			$user = C::t('common_member')->fetch_uid_by_username($queryparams['user']);
			if($user) {
				$queryparams['uid'] = $user['uid'];
			} else {
				$queryparams['uid'] = -1;
			}
		}
	}
	$ordercount = C::t('common_payment_order')->count_by_search($queryparams['uid'], $queryparams['type'], $queryparams['starttime'], $queryparams['endtime'], $queryparams['out_biz_no'], $queryparams['channel'], $queryparams['status']);
	$multipage = multi($ordercount, $_G['tpp'], $page, ADMINSCRIPT . "?action=plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders&" . http_build_query($queryparams));

	$tdstyles = array(
		'style="width: 220px;"',
		'style="width: 100px; text-align: center"',
		'',
		'style="width: 120px;"',
		'style="width: 100px; text-align: center"',
		'style="width: 100px; text-align: right"',
		'style="width: 100px; text-align: center"',
		'style="width: 160px; text-align: right"',
		'style="width: 100px; text-align: center"'
	);
	showtableheader('result');
	showsubtitle(array('ec_paymentorders_no', 'ec_paymentorders_type', 'ec_paymentorders_desc', 'ec_paymentorders_buyer', 'ec_paymentorders_channel', 'ec_paymentorders_amount', 'ec_paymentorders_status', $plang['ec_orders_date'], 'operation'), 'header', $tdstyles);
	if($ordercount > 0) {
		$order_list = C::t('common_payment_order')->fetch_all_by_search($queryparams['uid'], $queryparams['type'], $queryparams['starttime'], $queryparams['endtime'], $queryparams['out_biz_no'], $queryparams['channel'], $queryparams['status'], $start_limit, $_G['tpp']);
		foreach($order_list as $order) {
			if($order['uid']>0){
				$user = getuserbyuid($order['uid']);
				$username = $user['username'];
			}else{
				$username = '游客';
			}
			
			if(!$order['status'] && $order['expire_time'] < time()) {
				$order['status'] = 2;
			}

			$amountstr = number_format($order['amount'] / 100, 2, '.', ',');
			
			$status_text = $lang['ec_paymentorders_status_' . $order['status']];
			if($order['status'] == 1 && !$order['callback_status']) {
				$status_text .= '<br/><a class="order-retry" href="' . ADMINSCRIPT . '?action=plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders&op=retry&order_id=' . $order['id'] . '">'.$plang['ec_paymentorders_callback_tips'].'</a>';
			}

			$operations = '<a href="' . ADMINSCRIPT . '?action=plugins&operation=config&do=2&identifier=unifiedpay&pmod=admincp_orders&op=query&order_id=' . $order['id'] . '">' . $lang['detail'] . '</a>';

			showtablerow('class="order-status-' . $order['status'] . '"', $tdstyles, array(
				$order['out_biz_no'],
				$order['type_name'],
				$order['subject'] . ($order['description'] ? '<br/>' . $order['description'] : ''),
				$username . ' (' . $order['uid'] . ')' . '<br/>' . $order['clientip'] . ':' . $order['remoteport'],
				$channels[$order['channel']]['title'],
				$amountstr,
				$status_text,
				date('Y-m-d H:i:s', $order['dateline']) . '<br/>' . ($order['payment_time'] ? date('Y-m-d H:i:s', $order['payment_time']) : 'N/A'),
				$operations
			));
		}
		showsubmit('', '', '', '', $multipage);
	} else {
		showtablerow('', array('class="center" colspan="25"'), array($lang['ec_paymentorders_no_data']));
	}
	showtablefooter();
	showformfooter();
}